<template>
  <div class="sales-forecast">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/forecast' }">智能预测</el-breadcrumb-item>
        <el-breadcrumb-item>销售预测</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="toolbar-actions">
        <el-select v-model="selectedPeriod" placeholder="选择预测周期" style="width: 150px; margin-right: 10px">
          <el-option label="未来7天" value="7" />
          <el-option label="未来15天" value="15" />
          <el-option label="未来30天" value="30" />
          <el-option label="未来90天" value="90" />
        </el-select>
        <el-button type="primary" @click="handleForecast">
          <el-icon><MagicStick /></el-icon>
          开始预测
        </el-button>
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>
          导出报告
        </el-button>
      </div>
    </div>

    <!-- 预测概览卡片 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="overview-item">
            <div class="overview-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%)">
              <el-icon :size="30"><TrendCharts /></el-icon>
            </div>
            <div class="overview-info">
              <div class="overview-value">¥{{ forecastData.totalSales }}</div>
              <div class="overview-label">预测销售额</div>
              <div class="overview-trend up">
                <el-icon><Top /></el-icon> +15.8%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="overview-item">
            <div class="overview-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%)">
              <el-icon :size="30"><ShoppingCart /></el-icon>
            </div>
            <div class="overview-info">
              <div class="overview-value">{{ forecastData.totalOrders }}</div>
              <div class="overview-label">预测订单量</div>
              <div class="overview-trend up">
                <el-icon><Top /></el-icon> +12.3%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="overview-item">
            <div class="overview-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)">
              <el-icon :size="30"><User /></el-icon>
            </div>
            <div class="overview-info">
              <div class="overview-value">{{ forecastData.avgCustomers }}</div>
              <div class="overview-label">日均客户数</div>
              <div class="overview-trend up">
                <el-icon><Top /></el-icon> +8.5%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="overview-item">
            <div class="overview-icon" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)">
              <el-icon :size="30"><Money /></el-icon>
            </div>
            <div class="overview-info">
              <div class="overview-value">¥{{ forecastData.avgOrderValue }}</div>
              <div class="overview-label">客单价</div>
              <div class="overview-trend up">
                <el-icon><Top /></el-icon> +3.2%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 预测趋势图表 -->
    <el-row :gutter="20">
      <el-col :span="16">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span><el-icon><TrendCharts /></el-icon> 销售趋势预测</span>
              <el-radio-group v-model="chartType" size="small">
                <el-radio-button label="line">折线图</el-radio-button>
                <el-radio-button label="bar">柱状图</el-radio-button>
                <el-radio-button label="area">面积图</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="trendChartRef" style="height: 400px"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <span><el-icon><PieChart /></el-icon> 销售渠道分布预测</span>
          </template>
          <div ref="channelChartRef" style="height: 400px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 商品销售预测 -->
    <el-card shadow="hover" style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span><el-icon><Box /></el-icon> 热销商品预测 TOP 20</span>
          <el-input
            v-model="searchKeyword"
            placeholder="搜索商品"
            style="width: 200px"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </template>
      <el-table :data="productForecastData" stripe style="width: 100%">
        <el-table-column type="index" label="排名" width="70" />
        <el-table-column prop="productName" label="商品名称" min-width="200">
          <template #default="{ row }">
            <div class="product-info">
              <el-avatar :size="40" :src="row.image" shape="square" />
              <span>{{ row.productName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="currentSales" label="当前销量" width="120">
          <template #default="{ row }">
            {{ row.currentSales }}
          </template>
        </el-table-column>
        <el-table-column prop="forecastSales" label="预测销量" width="120">
          <template #default="{ row }">
            <span style="color: #409eff; font-weight: bold">{{ row.forecastSales }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="growthRate" label="增长率" width="100">
          <template #default="{ row }">
            <el-tag :type="row.growthRate > 0 ? 'success' : 'danger'">
              {{ row.growthRate > 0 ? '+' : '' }}{{ row.growthRate }}%
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="confidence" label="置信度" width="120">
          <template #default="{ row }">
            <el-progress 
              :percentage="row.confidence" 
              :color="getConfidenceColor(row.confidence)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleViewDetail(row)">
              <el-icon><View /></el-icon>详情
            </el-button>
            <el-button link type="success" @click="handleAnalyze(row)">
              <el-icon><DataAnalysis /></el-icon>分析
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 影响因素分析 -->
    <el-card shadow="hover" style="margin-top: 20px">
      <template #header>
        <span><el-icon><DataAnalysis /></el-icon> 影响因素分析</span>
      </template>
      <el-row :gutter="20">
        <el-col :span="12">
          <div ref="factorChartRef" style="height: 300px"></div>
        </el-col>
        <el-col :span="12">
          <el-table :data="factorData" style="width: 100%">
            <el-table-column prop="factor" label="影响因素" />
            <el-table-column prop="weight" label="权重" width="100">
              <template #default="{ row }">
                <el-progress :percentage="row.weight" :show-text="true" />
              </template>
            </el-table-column>
            <el-table-column prop="impact" label="影响程度" width="100">
              <template #default="{ row }">
                <el-tag :type="getImpactType(row.impact)">{{ row.impact }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-card>

    <!-- 预测准确度分析 -->
    <el-card shadow="hover" style="margin-top: 20px">
      <template #header>
        <span><el-icon><CircleCheck /></el-icon> 预测准确度分析</span>
      </template>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-statistic title="整体准确率" :value="94.5" suffix="%" />
          <el-progress :percentage="94.5" status="success" style="margin-top: 10px" />
        </el-col>
        <el-col :span="8">
          <el-statistic title="平均误差率" :value="5.5" suffix="%" />
          <el-progress :percentage="5.5" color="#f56c6c" style="margin-top: 10px" />
        </el-col>
        <el-col :span="8">
          <el-statistic title="置信区间" value="92.3% - 96.7%" />
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

// 选择的预测周期
const selectedPeriod = ref('30')
const chartType = ref('line')
const searchKeyword = ref('')

// 预测数据
const forecastData = ref({
  totalSales: '328.5万',
  totalOrders: '12,458',
  avgCustomers: '2,856',
  avgOrderValue: '286'
})

// 商品预测数据
const productForecastData = ref([
  {
    id: 1,
    productName: 'iPhone 15 Pro Max',
    category: '手机数码',
    image: 'https://via.placeholder.com/40',
    currentSales: 856,
    forecastSales: 1245,
    growthRate: 45.4,
    confidence: 92
  },
  {
    id: 2,
    productName: '华为Mate 60 Pro',
    category: '手机数码',
    image: 'https://via.placeholder.com/40',
    currentSales: 723,
    forecastSales: 1056,
    growthRate: 46.0,
    confidence: 89
  },
  {
    id: 3,
    productName: '小米14 Ultra',
    category: '手机数码',
    image: 'https://via.placeholder.com/40',
    currentSales: 645,
    forecastSales: 892,
    growthRate: 38.3,
    confidence: 87
  },
  {
    id: 4,
    productName: 'MacBook Pro M3',
    category: '电脑办公',
    image: 'https://via.placeholder.com/40',
    currentSales: 534,
    forecastSales: 756,
    growthRate: 41.6,
    confidence: 90
  },
  {
    id: 5,
    productName: 'iPad Air 2024',
    category: '平板电脑',
    image: 'https://via.placeholder.com/40',
    currentSales: 478,
    forecastSales: 623,
    growthRate: 30.3,
    confidence: 85
  }
])

// 影响因素数据
const factorData = ref([
  { factor: '历史销售趋势', weight: 35, impact: '高' },
  { factor: '季节性因素', weight: 25, impact: '中' },
  { factor: '促销活动', weight: 20, impact: '中' },
  { factor: '市场竞争', weight: 15, impact: '低' },
  { factor: '库存水平', weight: 5, impact: '低' }
])

// 图表引用
const trendChartRef = ref(null)
const channelChartRef = ref(null)
const factorChartRef = ref(null)

// 开始预测
const handleForecast = () => {
  ElMessage.success(`正在执行未来${selectedPeriod.value}天的销售预测...`)
}

// 导出报告
const handleExport = () => {
  ElMessage.success('报告导出成功')
}

// 查看详情
const handleViewDetail = (row) => {
  ElMessage.info(`查看商品详情：${row.productName}`)
}

// 分析
const handleAnalyze = (row) => {
  ElMessage.info(`分析商品：${row.productName}`)
}

// 获取置信度颜色
const getConfidenceColor = (confidence) => {
  if (confidence >= 90) return '#67c23a'
  if (confidence >= 80) return '#e6a23c'
  return '#f56c6c'
}

// 获取影响程度类型
const getImpactType = (impact) => {
  const typeMap = {
    '高': 'danger',
    '中': 'warning',
    '低': 'info'
  }
  return typeMap[impact] || ''
}

// 初始化图表
const initCharts = () => {
  // 销售趋势图表
  if (trendChartRef.value) {
    const trendChart = echarts.init(trendChartRef.value)
    const option = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['实际销售', '预测销售', '置信区间上限', '置信区间下限']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: ['第1天', '第5天', '第10天', '第15天', '第20天', '第25天', '第30天']
      },
      yAxis: {
        type: 'value',
        name: '销售额(万元)'
      },
      series: [
        {
          name: '实际销售',
          type: 'line',
          data: [8.5, 9.2, 10.1, 9.8, 10.5, 11.2, 10.8],
          itemStyle: { color: '#409eff' }
        },
        {
          name: '预测销售',
          type: 'line',
          data: [null, null, null, null, null, 11.5, 12.3],
          itemStyle: { color: '#67c23a' },
          lineStyle: { type: 'dashed' }
        },
        {
          name: '置信区间上限',
          type: 'line',
          data: [null, null, null, null, null, 12.5, 13.5],
          itemStyle: { color: '#e6a23c' },
          lineStyle: { type: 'dotted', opacity: 0.5 }
        },
        {
          name: '置信区间下限',
          type: 'line',
          data: [null, null, null, null, null, 10.5, 11.1],
          itemStyle: { color: '#f56c6c' },
          lineStyle: { type: 'dotted', opacity: 0.5 }
        }
      ]
    }
    trendChart.setOption(option)
  }

  // 渠道分布图表
  if (channelChartRef.value) {
    const channelChart = echarts.init(channelChartRef.value)
    const option = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '销售渠道',
          type: 'pie',
          radius: '50%',
          data: [
            { value: 1048, name: '线上商城' },
            { value: 735, name: '门店零售' },
            { value: 580, name: '批发' },
            { value: 484, name: '代理' },
            { value: 300, name: '其他' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    channelChart.setOption(option)
  }

  // 影响因素图表
  if (factorChartRef.value) {
    const factorChart = echarts.init(factorChartRef.value)
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        name: '权重(%)'
      },
      yAxis: {
        type: 'category',
        data: ['库存水平', '市场竞争', '促销活动', '季节性因素', '历史销售趋势']
      },
      series: [
        {
          name: '权重',
          type: 'bar',
          data: [5, 15, 20, 25, 35],
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#667eea' },
              { offset: 1, color: '#764ba2' }
            ])
          }
        }
      ]
    }
    factorChart.setOption(option)
  }
}

onMounted(() => {
  nextTick(() => {
    initCharts()
  })
})
</script>

<style scoped lang="scss">
.sales-forecast {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.toolbar {
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .toolbar-actions {
    display: flex;
    align-items: center;
  }
}

.overview-cards {
  margin-bottom: 20px;

  .overview-item {
    display: flex;
    gap: 15px;

    .overview-icon {
      width: 60px;
      height: 60px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
    }

    .overview-info {
      flex: 1;

      .overview-value {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 5px;
      }

      .overview-label {
        font-size: 14px;
        color: #909399;
        margin-bottom: 5px;
      }

      .overview-trend {
        font-size: 12px;
        display: inline-flex;
        align-items: center;
        gap: 3px;

        &.up {
          color: #67c23a;
        }

        &.down {
          color: #f56c6c;
        }
      }
    }
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  span {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: bold;
  }
}

.product-info {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>

